Layer 1 - LLM Abstraction
This layer is about abstracting the function of an LLM, so that you can think about prompting and output and tool use in a way that does not tie you to a specific LLM, its calling conventions, and the quirks of its specific library.
At this layer we have:
-
LLMBroker: This is the main entrypoint to the layer. It leverages an LLM specific Gateway, and is the primary interface for interacting with the LLM on the other side. The LLMBroker correctly handles text generation, structured output, and tool use.
-
ChatSession: This is a simple class that wraps the LLMBroker and provides a conversational interface to the LLM with context size management. It is a good starting point for building a chatbot.
-
OllamaGateway, OpenAIGateway, OMLXGateway: These are out-of-the-box adapters that will interact with models available through Ollama, OpenAI and oMLX.
Note:
- OpenAIGateway supports environment-variable defaults. If api_key is not provided, it uses OPENAI_API_KEY. If base_url is not provided, it uses OPENAI_API_ENDPOINT.
- Explicit constructor arguments always take precedence over environment variables.
-
LLMGateway: This is the abstract class that all LLM adapters must inherit from. It provides a common interface and isolation point for interacting with LLMs.
-
MessageBuilder: This is a utility class for constructing messages with text, images, and file contents using a fluent interface.
Architecture Overview
The following diagram illustrates how the key classes in Layer 1 relate to each other:
classDiagram
class LLMBroker {
+model: str
+adapter: LLMGateway
+tokenizer: TokenizerGateway
+tracer: TracerSystem
+generate(messages, tools, temperature) str
+generate_object(messages, object_model) BaseModel
}
class ChatSession {
+broker: LLMBroker
+messages: List[LLMMessage]
+chat(message) str
+clear_history()
}
class LLMGateway {
<<abstract>>
+complete(model, messages, tools) LLMGatewayResponse
+calculate_embeddings(text, model) List[float]
}
class OllamaGateway {
+complete(model, messages, tools) LLMGatewayResponse
+calculate_embeddings(text, model) List[float]
}
class OpenAIGateway {
+complete(model, messages, tools) LLMGatewayResponse
+calculate_embeddings(text, model) List[float]
}
class TokenizerGateway {
+encode(text) List
+decode(tokens) str
}
class TracerSystem {
<<interface>>
+record_llm_call()
+record_llm_response()
+record_tool_call()
}
class LLMGatewayResponse {
+content: str
+tool_calls: List[LLMToolCall]
+object: BaseModel
}
class LLMMessage {
+role: MessageRole
+content: str
+tool_calls: List[LLMToolCall]
}
class MessageBuilder {
+add_text(text) MessageBuilder
+add_image(path) MessageBuilder
+add_file(path) MessageBuilder
+build() LLMMessage
}
ChatSession --> LLMBroker : wraps
LLMBroker --> LLMGateway : uses via adapter
LLMBroker --> TokenizerGateway : uses
LLMBroker --> TracerSystem : uses (optional)
OllamaGateway --|> LLMGateway : extends
OpenAIGateway --|> LLMGateway : extends
LLMGateway --> LLMGatewayResponse : returns
LLMBroker --> LLMMessage : sends/receives
MessageBuilder --> LLMMessage : builds
LLMGatewayResponse --> LLMMessage : contains
Working with Embeddings
Mojentic provides embeddings functionality through the calculate_embeddings method in both the OllamaGateway and OpenAIGateway classes. Embeddings are vector representations of text that capture semantic meaning, making them useful for similarity comparisons, clustering, and other NLP tasks.
Usage Example
from mojentic.llm.gateways import OllamaGateway, OpenAIGateway
# Initialize the gateways
ollama_gateway = OllamaGateway()
openai_gateway = OpenAIGateway(api_key="your-api-key")
# Calculate embeddings using Ollama
text = "This is a sample text for embeddings."
ollama_embeddings = ollama_gateway.calculate_embeddings(
text=text,
model="mxbai-embed-large" # Default model for Ollama
)
# Calculate embeddings using OpenAI
openai_embeddings = openai_gateway.calculate_embeddings(
text=text,
model="text-embedding-3-large" # Default model for OpenAI
)
# Use the embeddings for similarity comparison, clustering, etc.
print(f"Ollama embeddings dimension: {len(ollama_embeddings)}")
print(f"OpenAI embeddings dimension: {len(openai_embeddings)}")
OpenAI splits long text into parts of at most 8191 tokens. It weights each part's embedding by its token count, then normalizes the mean to length 1.
Important Notes
- Available Models:
- For Ollama: Models like "mxbai-embed-large" (default), "nomic-embed-text" are commonly used
-
For OpenAI: Models like "text-embedding-3-large" (default), "text-embedding-3-small", "text-embedding-ada-002" are available
-
Embedding Dimensions:
- Different models produce embeddings with different dimensions
- Ollama's "mxbai-embed-large" typically produces 1024-dimensional embeddings
-
OpenAI's "text-embedding-3-large" typically produces 3072-dimensional embeddings
-
Performance Considerations:
- Embedding generation is generally faster and less resource-intensive than text generation
- Local embedding models (via Ollama) may be more cost-effective for high-volume applications
Working with Images
Mojentic supports sending images to LLMs using the MessageBuilder class. This allows you to perform image analysis, OCR, and other vision-based tasks with a clean, fluent interface.
Usage Example
from mojentic.llm import LLMBroker
from mojentic.llm import MessageBuilder
from pathlib import Path
# Initialize the LLM broker
llm = LLMBroker(model="gemma3:27b") # Use an image-capable model
# Build a message with an image
message = MessageBuilder("Describe what you see in this image.") \
.add_image(Path.cwd() / "images" / "example.jpg") \
.build()
# Generate a response
result = llm.generate(messages=[message])
print(result)
Important Notes
- Image-Capable Models: You must use an image-capable model to process images. Not all models support image analysis.
- For Ollama: Models like "gemma3", "llava", and "bakllava" support image analysis
-
For OpenAI: Models like "gpt-4-vision-preview" and "gpt-4o" support image analysis
-
Image Formats: Supported image formats include JPEG, PNG, GIF, and WebP.
-
Implementation Details:
- The
MessageBuilderhandles the appropriate encoding of images for different LLM providers - For Ollama: Images are passed as file paths (handled internally by MessageBuilder)
-
For OpenAI: Images are base64-encoded and included in the message content (handled internally by MessageBuilder)
-
Performance Considerations: Image analysis may require more tokens and processing time than text-only requests.
Building Blocks
mojentic.llm.LLMBroker
This class is responsible for managing interaction with a Large Language Model. It abstracts the user from the specific mechanics of the LLM and provides a common interface for generating responses.
Source code in src/mojentic/llm/llm_broker.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 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 | |
__init__(model, gateway=None, tokenizer=None, tracer=None, tool_runner=None, tool_context=None)
Create an instance of the LLMBroker.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model
|
str
|
The name of the model to use. |
required |
gateway
|
LLMGateway | None
|
The gateway to use for communication with the LLM. If None, a gateway is created that will utilize a local Ollama server. |
None
|
tokenizer
|
TokenizerGateway | None
|
The gateway to use for tokenization. This is used to log approximate token counts for
the LLM calls. If
None, tiktoken's |
None
|
tracer
|
TracerSystem | None
|
Optional tracer system to record LLM calls and responses. |
None
|
tool_runner
|
ToolRunner | None
|
Strategy for executing tool calls returned by the LLM. Defaults to
:class: |
None
|
Source code in src/mojentic/llm/llm_broker.py
generate(messages, tools=None, config=None, temperature=None, num_ctx=None, max_tokens=None, correlation_id=None)
Generate a text response from the LLM.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
messages
|
LLMMessage
|
A list of messages to send to the LLM. |
required |
tools
|
List[Tool]
|
A list of tools to use with the LLM. If a tool call is requested, the tool will be called and the output will be included in the response. |
None
|
config
|
Optional[CompletionConfig]
|
Configuration object for LLM completion (recommended). If provided with individual kwargs, a DeprecationWarning is emitted. |
None
|
temperature
|
Optional[float]
|
The temperature to use for the response. Deprecated: use config. |
None
|
num_ctx
|
Optional[int]
|
The number of context tokens to use. Deprecated: use config. |
None
|
max_tokens
|
Optional[int]
|
The maximum number of tokens to generate. Deprecated: use config. |
None
|
correlation_id
|
str
|
UUID string that is copied from cause-to-affect for tracing events. A new UUID is generated when omitted. |
None
|
Returns:
| Type | Description |
|---|---|
str
|
The response from the LLM. |
Raises:
| Type | Description |
|---|---|
MaxToolIterationsExceededError
|
If tool calls exceed config.max_tool_iterations. |
Source code in src/mojentic/llm/llm_broker.py
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 | |
generate_object(messages, object_model, config=None, temperature=None, num_ctx=None, max_tokens=None, correlation_id=None)
Generate a structured response from the LLM and return it as an object.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
messages
|
List[LLMMessage]
|
A list of messages to send to the LLM. |
required |
object_model
|
BaseModel
|
The class of the model to use for the structured response data. |
required |
config
|
Optional[CompletionConfig]
|
Configuration object for LLM completion (recommended). If provided with individual kwargs, a DeprecationWarning is emitted. |
None
|
temperature
|
Optional[float]
|
The temperature to use for the response. Deprecated: use config. |
None
|
num_ctx
|
Optional[int]
|
The number of context tokens to use. Deprecated: use config. |
None
|
max_tokens
|
Optional[int]
|
The maximum number of tokens to generate. Deprecated: use config. |
None
|
correlation_id
|
str
|
UUID string that is copied from cause-to-affect for tracing events. A new UUID is generated when omitted. |
None
|
Returns:
| Type | Description |
|---|---|
BaseModel
|
An instance of the model class provided containing the structured response data. |
Source code in src/mojentic/llm/llm_broker.py
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 | |
generate_response(messages, tools=None, config=None, correlation_id=None)
Return one native model response without executing tools or changing history.
The caller assembles context and decides when to dispatch returned calls. Provider failures propagate; no retry or tool iteration occurs here. A new correlation ID is generated when none is supplied.
Source code in src/mojentic/llm/llm_broker.py
generate_stream(messages, tools=None, config=None, temperature=None, num_ctx=None, max_tokens=None, correlation_id=None)
Generate a streaming text response from the LLM.
This method mirrors generate() but yields content chunks as they arrive from the LLM, providing a better user experience for long-running requests. When tool calls are detected, tools are executed and the LLM is called recursively, with the new response also being streamed.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
messages
|
List[LLMMessage]
|
A list of messages to send to the LLM. |
required |
tools
|
List[Tool]
|
A list of tools to use with the LLM. If a tool call is requested, the tool will be called and the output will be included in the response. |
None
|
config
|
Optional[CompletionConfig]
|
Configuration object for LLM completion (recommended). If provided with individual kwargs, a DeprecationWarning is emitted. |
None
|
temperature
|
Optional[float]
|
The temperature to use for the response. Deprecated: use config. |
None
|
num_ctx
|
Optional[int]
|
The number of context tokens to use. Deprecated: use config. |
None
|
max_tokens
|
Optional[int]
|
The maximum number of tokens to generate. Deprecated: use config. |
None
|
correlation_id
|
str
|
UUID string that is copied from cause-to-affect for tracing events. A new UUID is generated when omitted. |
None
|
Yields:
| Type | Description |
|---|---|
str
|
Content chunks as they arrive from the LLM. |
Raises:
| Type | Description |
|---|---|
MaxToolIterationsExceededError
|
If tool calls exceed config.max_tool_iterations. |
Source code in src/mojentic/llm/llm_broker.py
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 | |
generate_stream_events(messages, config=None, correlation_id=None)
Stream one model turn as events that end with terminal completion evidence.
Use this when incomplete output must never be mistaken for a result. The stream
yields :class:StreamContent events and ends with exactly one terminal event:
:class:StreamCompleted when the provider finished the turn normally, or
:class:StreamError otherwise. Content yielded before a :class:StreamError is
evidence of what the provider sent, not a usable result.
The broker sends one request with no tools, forces zero tool iterations and never
retries. Call close() on the generator to cancel the HTTP request. Use
contextlib.closing around a loop that may break early. A retained generator
stays open after break. A gateway without
complete_stream_events yields a single STREAM_EVENTS_UNSUPPORTED error
without sending a request.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
messages
|
List[LLMMessage]
|
The messages to send. |
required |
config
|
Optional[CompletionConfig]
|
Configuration for the request. |
None
|
correlation_id
|
Optional[str]
|
UUID string that is copied from cause-to-affect for tracing events. A new UUID is generated when omitted. |
None
|
Yields:
| Type | Description |
|---|---|
StreamEvent
|
Content events followed by exactly one terminal event. |
Source code in src/mojentic/llm/llm_broker.py
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 | |
last_stream_metrics
property
writable
Latest dispatched stream evidence, including failure and local close.
mojentic.llm.ChatSession
This class is responsible for managing the state of a conversation with the LLM.
Source code in src/mojentic/llm/chat_session.py
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 | |
__init__(llm, system_prompt='You are a helpful assistant.', tools=None, max_context=32768, tokenizer_gateway=None, config=None, temperature=None)
Create an instance of the ChatSession.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
llm
|
LLMBroker
|
The broker to use for generating responses. |
required |
system_prompt
|
str
|
The prompt to use for the system messages. Defaults to "You are a helpful assistant." |
'You are a helpful assistant.'
|
tools
|
List[LLMTool]
|
The tools you want to make available to the LLM. Defaults to None. |
None
|
max_context
|
int
|
The maximum number of tokens to keep in the context. Defaults to 32768. |
32768
|
tokenizer_gateway
|
TokenizerGateway
|
The gateway to use for tokenization. If None, |
None
|
config
|
Optional[CompletionConfig]
|
Configuration object for LLM completion. If None, one is created from temperature. max_context is only a local trimming budget. |
None
|
temperature
|
float
|
The temperature to use for the response. Unspecified by default. Deprecated: use config. |
None
|
Source code in src/mojentic/llm/chat_session.py
insert_message(message)
Add a message onto the end of the chat session. If the total token count exceeds the max context, the oldest messages are removed.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
message
|
LLMMessage
|
The message to add to the chat session. |
required |
Source code in src/mojentic/llm/chat_session.py
last_stream_metrics
property
Timing evidence for the latest completion in this session's broker.
send(query)
Send a query to the LLM and return the response. Also records the query and response in the ongoing chat session.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
query
|
str
|
The query to send to the LLM. |
required |
Returns:
| Type | Description |
|---|---|
str
|
The response from the LLM. |
Source code in src/mojentic/llm/chat_session.py
send_stream(query)
Send a query to the LLM and yield response chunks as they arrive. Records the query and the full assembled response in the ongoing chat session after the stream is consumed.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
query
|
str
|
The query to send to the LLM. |
required |
Yields:
| Type | Description |
|---|---|
str
|
Content chunks from the LLM response as they arrive. |
Source code in src/mojentic/llm/chat_session.py
mojentic.llm.gateways.LLMGateway
This is an abstract class from which specific LLM gateways are derived.
To create a new gateway, inherit from this class and implement the complete method.
Source code in src/mojentic/llm/gateways/llm_gateway.py
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 | |
calculate_embeddings(text, model=None)
Calculate embeddings for the given text using the specified model.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
text
|
str
|
The text to calculate embeddings for. |
required |
model
|
str
|
The name of the model to use for embeddings. Default value depends on the implementation. |
None
|
Returns:
| Type | Description |
|---|---|
List[Any]
|
The embeddings for the text. |
Source code in src/mojentic/llm/gateways/llm_gateway.py
complete(model, messages, object_model=None, tools=None, config=None, temperature=None, num_ctx=None, max_tokens=None)
Complete the LLM request.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model
|
str
|
The name of the model to use, as appears in |
required |
messages
|
List[LLMMessage]
|
A list of messages to send to the LLM. |
required |
object_model
|
Optional[BaseModel]
|
The model to use for validating the response. |
None
|
tools
|
Optional[List[LLMTool]]
|
A list of tools to use with the LLM. If a tool call is requested, the tool will be called and the output will be included in the response. |
None
|
config
|
Optional[CompletionConfig]
|
Configuration object for LLM completion (recommended over individual kwargs). |
None
|
temperature
|
float
|
The temperature to use for the response. Unspecified by default. (Deprecated: use config) |
None
|
num_ctx
|
int
|
The number of context tokens to use. Unspecified by default. (Deprecated: use config) |
None
|
max_tokens
|
int
|
The maximum number of tokens to generate. Unspecified by default. (Deprecated: use config) |
None
|
Returns:
| Type | Description |
|---|---|
LLMGatewayResponse
|
The response from the Ollama service. |
Source code in src/mojentic/llm/gateways/llm_gateway.py
get_available_models()
Get the list of available models.
Returns:
| Type | Description |
|---|---|
List[str]
|
The list of available models. |
get_model_context_window(model)
Return advertised metadata, or None when discovery is unsupported.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model
|
str
|
Exact provider model identifier. |
required |
Returns:
| Type | Description |
|---|---|
ModelContextWindow | None
|
Positive advertised window and source field, or not advertised. |
Raises:
| Type | Description |
|---|---|
TransportError
|
The provider could not be reached (HTTP gateways). |
HTTPStatusError
|
The provider returned a non-success status (HTTP gateways). |
ValueError
|
The response body or advertised metadata is malformed. |
Source code in src/mojentic/llm/gateways/llm_gateway.py
mojentic.llm.gateways.OllamaGateway
Bases: LLMGateway
This class is a gateway to the Ollama LLM service.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
host
|
str
|
The Ollama host to connect to. Defaults to "http://localhost:11434". |
'http://localhost:11434'
|
headers
|
dict
|
The headers to send with the request. Defaults to an empty dict. |
None
|
timeout
|
optional
|
The request timeout passed to the Ollama client. |
None
|
recovery_policy
|
RecoveryPolicy
|
Opt in to ordinary, structured, and tool-capable streaming request recovery. |
None
|
recovery_call
|
RecoveryCall
|
Cancellation for a synchronous broker/session operation. Use a fresh call per operation. |
None
|
stream_transport
|
OllamaStreamTransport
|
The transport |
None
|
Source code in src/mojentic/llm/gateways/ollama.py
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 | |
calculate_embeddings(text, model='mxbai-embed-large')
Calculate embeddings for the given text using the specified model.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
text
|
str
|
The text to calculate embeddings for. |
required |
model
|
str
|
The name of the model to use for embeddings. Defaults to "mxbai-embed-large". |
'mxbai-embed-large'
|
Returns:
| Type | Description |
|---|---|
list
|
The embeddings for the text. |
Source code in src/mojentic/llm/gateways/ollama.py
complete(**args)
Complete the LLM request by delegating to the Ollama service.
Keyword Arguments
model : str
The name of the model to use, as appears in ollama list.
messages : List[LLMMessage]
A list of messages to send to the LLM.
object_model : Optional[BaseModel]
The model to use for validating the response.
tools : Optional[List[LLMTool]]
A list of tools to use with the LLM. If a tool call is requested, the tool will be called and the output
will be included in the response.
temperature : float, optional
The temperature to use for the response. Unspecified by default.
num_ctx : int, optional
The number of context tokens to use. Unspecified by default.
max_tokens : int, optional
The maximum number of tokens to generate. Unspecified by default.
Returns:
| Type | Description |
|---|---|
LLMGatewayResponse
|
The response from the Ollama service. |
Source code in src/mojentic/llm/gateways/ollama.py
complete_stream(**args)
Stream the LLM response from Ollama service.
Keyword Arguments
model : str
The name of the model to use, as appears in ollama list.
messages : List[LLMMessage]
A list of messages to send to the LLM.
tools : Optional[List[LLMTool]]
A list of tools to use with the LLM. If a tool call is requested, the tool will be called and the output
will be included in the response.
temperature : float, optional
The temperature to use for the response. Unspecified by default.
num_ctx : int, optional
The number of context tokens to use. Unspecified by default.
max_tokens : int, optional
The maximum number of tokens to generate. Unspecified by default.
Returns:
| Type | Description |
|---|---|
Iterator[StreamingResponse]
|
An iterator of StreamingResponse objects containing response chunks. |
Source code in src/mojentic/llm/gateways/ollama.py
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 | |
complete_stream_events(model, messages, config)
Stream one turn as events, with terminal completion evidence.
Sends one streaming request with no tools. The turn completes only when Ollama
reports done: true with done_reason: "stop". Closing the generator closes
the HTTP request.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model
|
str
|
The name of the model to use, as appears in |
required |
messages
|
List[LLMMessage]
|
The messages to send. |
required |
config
|
CompletionConfig
|
Configuration for the request. |
required |
Yields:
| Type | Description |
|---|---|
StreamEvent
|
Content events followed by exactly one terminal event. |
Source code in src/mojentic/llm/gateways/ollama.py
complete_stream_with_recovery(call=None, **args)
async
Stream one tool-capable completion with explicit recovery terminal events.
Consume completed or failed to determine the outcome. Closing this
iterator closes locally owned HTTP; it does not prove remote termination.
Raw complete_stream_events remains a single-turn compatibility API.
Source code in src/mojentic/llm/gateways/ollama.py
complete_with_recovery(call=None, **args)
async
Complete one ordinary or structured request with safe recovery metadata.
Raises:
| Type | Description |
|---|---|
RecoveryError
|
Provider, protocol, capture, cancellation, or recovery admission failed. |
ValueError
|
No recovery policy is configured. |
Source code in src/mojentic/llm/gateways/ollama.py
get_available_models()
Get the list of available local models, sorted alphabetically.
Returns:
| Type | Description |
|---|---|
List[str]
|
The list of available models, sorted alphabetically. |
Source code in src/mojentic/llm/gateways/ollama.py
get_model_context_window(model)
Discover model metadata without changing completion options.
Source code in src/mojentic/llm/gateways/ollama.py
pull_model(model)
Pull the model from the Ollama service.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model
|
str
|
The name of the model to pull. |
required |
recovery_capabilities()
Report recovery support without implying remote cancellation or idempotency.
mojentic.llm.gateways.OpenAIGateway
Bases: LLMGateway
This class is a gateway to the OpenAI LLM service.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
api_key
|
str
|
The OpenAI API key to use. If not provided, defaults to the value of the OPENAI_API_KEY environment variable. |
None
|
base_url
|
str
|
The base URL for the OpenAI API. If not provided, defaults to the value of the OPENAI_API_ENDPOINT environment variable, or None if not set. |
None
|
stream_transport
|
OpenAIStreamTransport
|
The transport |
None
|
recovery_policy
|
RecoveryPolicy
|
Opt in for ordinary, structured and tool-capable streaming completion. Owned HTTP bypasses SDK retries and redirects and has no active read timeout. |
None
|
recovery_call
|
RecoveryCall
|
Cancellation for a synchronous operation. Use a fresh call per operation. |
None
|
Source code in src/mojentic/llm/gateways/openai.py
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 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 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 | |
calculate_embeddings(text, model='text-embedding-3-large')
Calculate embeddings for the given text using the specified OpenAI model.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
text
|
str
|
The text to calculate embeddings for. |
required |
model
|
str
|
The name of the OpenAI embeddings model to use. Defaults to "text-embedding-3-large". |
'text-embedding-3-large'
|
Returns:
| Type | Description |
|---|---|
list
|
The mean of the part embeddings, weighted by each part's token count and normalized to length 1. |
Source code in src/mojentic/llm/gateways/openai.py
complete(**kwargs)
Complete the LLM request by delegating to the OpenAI service.
Keyword Arguments
model : str The name of the model to use. messages : List[LLMMessage] A list of messages to send to the LLM. object_model : Optional[Type[BaseModel]] The model to use for validating the response. tools : Optional[List[LLMTool]] A list of tools to use with the LLM. If a tool call is requested, the tool will be called and the output will be included in the response. temperature : float, optional The temperature to use for the response. Unspecified by default. num_ctx : int, optional The number of context tokens to use. Unspecified by default. max_tokens : int, optional The maximum number of tokens to generate. Unspecified by default.
Returns:
| Type | Description |
|---|---|
LLMGatewayResponse
|
The response from the OpenAI service. |
Source code in src/mojentic/llm/gateways/openai.py
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 | |
complete_stream(**kwargs)
Stream the LLM response from OpenAI service.
OpenAI streams tool call arguments incrementally, so we need to accumulate them and yield complete tool calls only when the stream finishes.
Keyword Arguments
model : str The name of the model to use. messages : List[LLMMessage] A list of messages to send to the LLM. tools : Optional[List[LLMTool]] A list of tools to use with the LLM. Tool calls will be accumulated and yielded when complete. temperature : float, optional The temperature to use for the response. Unspecified by default. num_ctx : int, optional The number of context tokens to use. Unspecified by default. max_tokens : int, optional The maximum number of tokens to generate. Unspecified by default.
Returns:
| Type | Description |
|---|---|
Iterator[StreamingResponse]
|
An iterator of StreamingResponse objects containing response chunks. |
Source code in src/mojentic/llm/gateways/openai.py
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 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 | |
complete_stream_events(model, messages, config)
Stream one turn as events, with terminal completion evidence.
Sends one streaming request with no tools, no retries and
stream_options: {"include_usage": true}. The turn completes only when the
provider reports finish_reason: "stop" and then sends data: [DONE].
Closing the generator closes the HTTP request.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model
|
str
|
The name of the model to use. |
required |
messages
|
List[LLMMessage]
|
The messages to send. |
required |
config
|
CompletionConfig
|
Configuration for the request. |
required |
Yields:
| Type | Description |
|---|---|
StreamEvent
|
Content events followed by exactly one terminal event. |
Source code in src/mojentic/llm/gateways/openai.py
complete_stream_with_recovery(call=None, **args)
async
Recover before semantic observation; closing cancels owned HTTP resources.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
call
|
RecoveryCall
|
Cancellation for this operation, overriding the gateway call. |
None
|
**args
|
Model, messages, tools and controls accepted by |
{}
|
Yields:
| Type | Description |
|---|---|
RecoveryStreamEvent
|
Progress and provider telemetry followed by one completed or failed outcome. Private semantic fields require explicit inspection for serialization. |
Raises:
| Type | Description |
|---|---|
ValueError
|
No recovery policy is configured. |
Source code in src/mojentic/llm/gateways/openai.py
complete_with_recovery(call=None, **args)
async
Recover an ordinary or structured turn with private typed failure evidence.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
call
|
RecoveryCall
|
Cancellation for this operation, overriding the gateway call. |
None
|
**args
|
Model, messages, tools, schema and controls accepted by |
{}
|
Returns:
| Type | Description |
|---|---|
LLMGatewayResponse
|
Provider response with a recovery report; tools are returned for the broker. |
Raises:
| Type | Description |
|---|---|
RecoveryError
|
Completion failed, recovery was refused, or cancellation was requested. |
ValueError
|
No recovery policy is configured. |
Source code in src/mojentic/llm/gateways/openai.py
get_available_models()
Get the list of available OpenAI models, sorted alphabetically.
Returns:
| Type | Description |
|---|---|
list[str]
|
The list of available models, sorted alphabetically. |
Source code in src/mojentic/llm/gateways/openai.py
get_model_context_window(model)
Return exact registry metadata without a network request or pattern fallback.
Source code in src/mojentic/llm/gateways/openai.py
recovery_capabilities()
Report completion recovery; remote inference termination remains unknown.
mojentic.llm.gateways.OMLXGateway
Bases: LLMGateway
A gateway to an oMLX <https://github.com/jundot/omlx>_ server, an LLM server for Apple Silicon.
oMLX speaks the OpenAI chat completions protocol. This gateway sends requests with no
per-model adaptation, maps reasoning_content to thinking, and keeps usage exactly
as the server reports it.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
host
|
str
|
The server host, without |
None
|
api_key
|
str
|
Sent as |
None
|
timeout
|
float
|
The timeout in seconds for every request, including model load. Defaults to
|
None
|
transport
|
OMLXTransport
|
Transport for legacy completions, embeddings and model management. Opt-in completion recovery uses a dedicated owned HTTP transport. |
None
|
recovery_policy
|
RecoveryPolicy
|
Opt in to ordinary, structured and streaming request recovery. Recovery disables the active response read timeout; other timeout settings remain. |
None
|
recovery_call
|
RecoveryCall
|
Cancellation for a synchronous operation. Use a fresh call per operation. |
None
|
Notes
Legacy non-2xx responses raise httpx.HTTPStatusError. Recovery-enabled
completion paths raise typed RecoveryError with private cause inspection.
Raw complete_stream_events remains single-request and reports provider errors.
Source code in src/mojentic/llm/gateways/omlx.py
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 | |
calculate_embeddings(text, model=None)
Calculate embeddings for the text in one request, with no client-side chunking.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
text
|
str
|
The text to embed. |
required |
model
|
str
|
The embedding model id. Required: oMLX has no standard embedding model. |
None
|
Returns:
| Type | Description |
|---|---|
List[float]
|
The embedding. |
Raises:
| Type | Description |
|---|---|
ValueError
|
When |
HTTPStatusError
|
A 400 |
Source code in src/mojentic/llm/gateways/omlx.py
complete(model, messages, object_model=None, tools=None, config=None, temperature=None, num_ctx=None, max_tokens=None)
Complete one chat turn.
When a structured output request comes back with a Warning header, oMLX did not
enforce the format. The header value goes in metadata["response_format_warning"]
and a warning is logged. The content is still returned and, with object_model,
still validated.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model
|
str
|
The model id, as |
required |
messages
|
List[LLMMessage]
|
The conversation. |
required |
object_model
|
Optional[Type[BaseModel]]
|
Request JSON schema output with this model's schema and validate the content against it. |
None
|
tools
|
Optional[List[LLMTool]]
|
Tools to offer. Requested calls come back in |
None
|
config
|
Optional[CompletionConfig]
|
Temperature, token limit, reasoning effort and response format. When None, one is
built from |
None
|
temperature
|
float | None
|
Deprecated: use |
None
|
num_ctx
|
float | None
|
Deprecated: use |
None
|
max_tokens
|
float | None
|
Deprecated: use |
None
|
Returns:
| Type | Description |
|---|---|
LLMGatewayResponse
|
Content, thinking, tool calls, usage, provider model, finish reason and metadata.
|
Source code in src/mojentic/llm/gateways/omlx.py
complete_stream(model, messages, object_model=None, tools=None, config=None, temperature=None, num_ctx=None, max_tokens=None)
Stream one chat turn as legacy chunks.
Content arrives as content chunks and reasoning_content as thinking chunks. Tool
calls are yielded together, complete, when the turn finishes with tool_calls.
Keep-alive frames are dropped. Closing the generator closes the request.
Parameters are as for :meth:complete, except that object_model is not supported.
Raises:
| Type | Description |
|---|---|
NotImplementedError
|
When |
Source code in src/mojentic/llm/gateways/omlx.py
complete_stream_events(model, messages, config)
Stream one turn as events, with terminal completion evidence.
Sends one streaming request with no tools, no retries and
stream_options: {"include_usage": true}. Keep-alive frames are dropped before
parsing, so they never become evidence. reasoning_content produces no events. The
turn completes only when oMLX reports finish_reason: "stop" and then sends
data: [DONE]. Closing the generator closes the HTTP request.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model
|
str
|
The model id. |
required |
messages
|
List[LLMMessage]
|
The messages to send. |
required |
config
|
CompletionConfig
|
Configuration for the request. |
required |
Yields:
| Type | Description |
|---|---|
StreamEvent
|
Content events followed by exactly one terminal event. |
Source code in src/mojentic/llm/gateways/omlx.py
complete_stream_with_recovery(call=None, **args)
async
Yield progress and exactly one completed or failed recovery outcome.
Closing the iterator cancels owned local HTTP; remote termination is unknown. Raw complete_stream_events remains a single-request compatibility API.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
call
|
RecoveryCall
|
Cancellation for this operation, overriding the gateway call. |
None
|
**args
|
The model, messages, tools and controls accepted by |
{}
|
Yields:
| Type | Description |
|---|---|
RecoveryStreamEvent
|
Provider progress followed by one completed or failed terminal outcome. |
Raises:
| Type | Description |
|---|---|
ValueError
|
No recovery policy is configured. |
Source code in src/mojentic/llm/gateways/omlx.py
complete_with_recovery(call=None, **args)
async
Recover one ordinary or structured completion, retaining typed failure evidence.
Recovery bypasses the legacy transport and disables active read timeouts.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
call
|
RecoveryCall
|
Cancellation for this operation, overriding the gateway call. |
None
|
**args
|
The model, messages, tools, schema and controls accepted by |
{}
|
Returns:
| Type | Description |
|---|---|
LLMGatewayResponse
|
Provider response with a typed recovery report. |
Raises:
| Type | Description |
|---|---|
RecoveryError
|
Recovery refused, interrupted, cancelled or received an invalid response. |
ValueError
|
No recovery policy is configured. |
Source code in src/mojentic/llm/gateways/omlx.py
get_available_models()
Get the ids of the models the server offers, sorted alphabetically.
Returns:
| Type | Description |
|---|---|
List[str]
|
The model ids. |
Source code in src/mojentic/llm/gateways/omlx.py
get_model_context_window(model)
Discover exact model metadata using the configured host and credentials.
load_model(model)
Load a model into memory and wait until it is there.
A chat request loads its model automatically; use this to warm a model up ahead of time. The gateway timeout covers the wait.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model
|
str
|
The model id. |
required |
Source code in src/mojentic/llm/gateways/omlx.py
recovery_capabilities()
unload_model(model)
Unload a model from memory.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model
|
str
|
The model id. |
required |
Raises:
| Type | Description |
|---|---|
HTTPStatusError
|
A 400 |
Source code in src/mojentic/llm/gateways/omlx.py
mojentic.llm.gateways.models.LLMMessage
Bases: BaseModel
A message to be sent to the LLM. These would accumulate during a chat session with an LLM.
Attributes:
| Name | Type | Description |
|---|
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
role
|
MessageRole
|
|
<MessageRole.User: 'user'>
|
content
|
str | None
|
|
None
|
thinking
|
str | None
|
|
None
|
object
|
BaseModel | None
|
|
None
|
tool_calls
|
list[LLMToolCall] | None
|
|
None
|
image_paths
|
list[str] | None
|
|
None
|
Source code in src/mojentic/llm/gateways/models.py
mojentic.llm.gateways.models.LLMToolCall
Bases: BaseModel
A tool call to be made available to the LLM.
Attributes:
| Name | Type | Description |
|---|
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
id
|
str | None
|
|
None
|
name
|
str
|
|
required |
arguments
|
dict[str, Any]
|
|
required |
Source code in src/mojentic/llm/gateways/models.py
mojentic.llm.gateways.models.LLMGatewayResponse
Bases: BaseModel
The response from the LLM gateway, abstracting you from the quirks of a specific LLM.
Attributes:
| Name | Type | Description |
|---|
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
content
|
str | dict[str, str] | None
|
The content of the response. |
None
|
object
|
BaseModel | None
|
Parsed response object |
None
|
tool_calls
|
list[LLMToolCall]
|
List of requested tool calls from the LLM. |
<dynamic>
|
thinking
|
str | None
|
Model thinking/reasoning trace (populated by some providers) |
None
|
usage
|
dict[str, Any] | None
|
|
None
|
model
|
str | None
|
|
None
|
finish_reason
|
str | None
|
|
None
|
metadata
|
dict[str, Any]
|
dict() -> new empty dictionary dict(mapping) -> new dictionary initialized from a mapping object's (key, value) pairs dict(iterable) -> new dictionary initialized as if via: d = {} for k, v in iterable: d[k] = v dict(**kwargs) -> new dictionary initialized with the name=value pairs in the keyword argument list. For example: dict(one=1, two=2) |
<class 'dict'>
|
recovery_report
|
RecoveryReport | None
|
|
None
|